package com.atguigu.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.cart.feign.ProductFeignService;
import com.atguigu.gulimall.cart.interceptor.CartInterceptor;
import com.atguigu.gulimall.cart.service.CartService;
import com.atguigu.gulimall.cart.to.UserInfoTo;
import com.atguigu.gulimall.cart.vo.Cart;
import com.atguigu.gulimall.cart.vo.CartItem;
import com.atguigu.gulimall.cart.vo.SkuInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.swing.*;
import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    ThreadPoolExecutor executor;

    public static final String CART_PREFIX="gulimall:cart:";

    @Override
    public CartItem addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {

        CartItem cartItem = new CartItem();
        //远程查询当前要添加的商品信息
        CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
            R skuInfo = productFeignService.getSkuInfo(skuId);
            String info = JSON.toJSONString(skuInfo.get("skuInfo"));
            SkuInfoVo skuInfoVo = JSON.parseObject(info, SkuInfoVo.class);
            cartItem.setCheck(true);
            cartItem.setCount(num);
            cartItem.setSkuId(skuId);
            cartItem.setPrice(new BigDecimal("0"));
            if (skuInfoVo!=null){
                //商品添加到购物车
                cartItem.setImages(skuInfoVo.getSkuDefaultImg());
                cartItem.setTitle(skuInfoVo.getSkuTitle());
                cartItem.setPrice(skuInfoVo.getPrice());
            }

        }, executor);

        //远程查询sku的组合信息
        CompletableFuture<Void> getSkuSaleAttrValues = CompletableFuture.runAsync(() -> {
            List<String> skuSaleAttrValues = productFeignService.getSkuSaleAttrValues(skuId);
            if (skuSaleAttrValues!=null && skuSaleAttrValues.size()>0){
                cartItem.setSkuAttr(skuSaleAttrValues);
            }
        }, executor);

        //等待所有任务都完成
        CompletableFuture.allOf(getSkuInfoTask, getSkuSaleAttrValues).get();

        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String s = JSON.toJSONString(cartItem);
        String res = (String) cartOps.get(skuId.toString());

        if (!StringUtils.isEmpty(res)){
            //缓存中有该商品
            CartItem item = JSON.parseObject(res, cartItem.getClass());
            item.setCount(item.getCount()+num);
            s=JSON.toJSONString(item);
        }
        cartOps.put(skuId.toString(),s);

        return cartItem;
    }

    @Override
    public CartItem getCartItem(Long skuId) {

        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String res = (String) cartOps.get(skuId.toString());
        return JSON.parseObject(res,CartItem.class);
    }

    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {
        Cart cart = new Cart();
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String tempCartKey=CART_PREFIX + userInfoTo.getUserKey();
        if (userInfoTo.getUserId()!=null){
            //已登录
            //查询临时购物车，如果临时购物车的数据没有合并，则进行合并
            List<CartItem> tempCartItems = getCartItems(tempCartKey);
            if (tempCartItems!=null && tempCartItems.size()>0){
                for (CartItem cartItem : tempCartItems) {
                    addToCart(cartItem.getSkuId(),cartItem.getCount());
                }

                //清除临时购物车数据
                clearCart(tempCartKey);
            }

            //获取登录后的购物车数据[包含临时的购物车数据]
            String cartKey =CART_PREFIX+userInfoTo.getUserId();
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setCartItems(cartItems);

            return cart;
        }
        //未登录
        List<CartItem> cartItems = getCartItems(tempCartKey);
        cart.setCartItems(cartItems);
        return cart;
    }

    @Override
    public void clearCart(String cartKey) {
        redisTemplate.delete(cartKey);
    }

    @Override
    public void checkItem(Long skuId, Integer check) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(check==1?true:false);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(),JSON.toJSONString(cartItem));
    }

    @Override
    public void changeCountItem(Long skuId, Integer num) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(num);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(),JSON.toJSONString(cartItem));
    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();

        cartOps.delete(skuId.toString());
    }

    @Override
    public List<CartItem> getUserCartItems() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId()!=null){
            String cartKey=CART_PREFIX+userInfoTo.getUserId();
            List<CartItem> cartItems = getCartItems(cartKey);
            if (cartItems!=null &&cartItems.size()>0){
                //获取所有被选中的购物项
                List<CartItem> collect = cartItems.stream().filter(CartItem::getCheck)
                        .map(item->{
                            R price = productFeignService.getPrice(item.getSkuId());
                            //TODO 更新为最新价格
                            String data = (String) price.get("data");
                            item.setPrice(new BigDecimal(data));
                            return item;
                        })
                        .collect(Collectors.toList());
                return collect;
            }
        }

       return null;
    }

    /**
     * 获取到需要操作的购物车
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();

        String cartKey="";
        if (userInfoTo.getUserId()!=null){
            cartKey=CART_PREFIX+userInfoTo.getUserId();
        }else{
            cartKey=CART_PREFIX+userInfoTo.getUserKey();
        }

        BoundHashOperations<String, Object, Object> operations= redisTemplate.boundHashOps(cartKey);

        return operations;
    }

    //根据key获取购物车数据
    private List<CartItem> getCartItems(String cartKey){
        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(cartKey);
        List<Object> values = hashOps.values();
        if (values!=null && values.size()>0){
            List<CartItem> collect = values.stream().map((obj) -> {
                CartItem cartItem = JSON.parseObject((String) obj, CartItem.class);

                return cartItem;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }


}
